package top.psjj.mall.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import top.psjj.mall.comment.Constant;
import top.psjj.mall.comment.Result;
import top.psjj.mall.exception.MallExceptionEnum;
import top.psjj.mall.model.po.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/*
* 用户过滤器*/
public class UserFilter implements Filter {
    public static User currentUser;
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        resp.setContentType("application/json;charset=utf-8");
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        //获得用户信息
        currentUser = (User) req.getSession().getAttribute(Constant.User.CURRENT_USER);
        //转换为json数据
        ObjectMapper objectMapper = new ObjectMapper();
        //未登过滤器
        if(currentUser==null){
            String result = objectMapper.writeValueAsString(Result.error(MallExceptionEnum.NEED_LOGIN));
            resp.getWriter().write(result);
            return;
        }else {
            filterChain.doFilter(req,resp);
        }
    }
}
